#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: categories.py
@contact: zwb15083976291@163.com
@time: 2022/02/25
"""
from rest_framework.generics import GenericAPIView

from common.models import BlogCategorie
from common.serializers.serializer import CategoriesSerializer
from utils.responses import CommonResponse, CommonAPIResponseStatus
from utils.views import BaseGenericAPIView


class CategorieListView(BaseGenericAPIView):
    serializer_class = CategoriesSerializer
    diff_methods_request_params = dict(get=dict(optional=['id']))

    def get(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        many = True
        if self.query_data.get('id', None) is not None:
            query_set = BlogCategorie.objects.filter(id=self.query_data.get('id')).first()
            many = False
        else:
            query_set = BlogCategorie.objects.order_by('-categorie_count').all()
        serial_fields = ['id', 'categorie_name', 'categorie_count']
        return CommonResponse(
            data=CategoriesSerializer(instance=query_set, many=many,
                                      serial_fields=serial_fields).data)
